package com.xinz.server.socket;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;

import com.xinz.srmi.Buffer;


public class SpotProtocalEncoder extends OneToOneEncoder {
	
//	final String SRMI_SESSION = "srmi_session";
//	@Override
//	public void encode(IoSession session, Object message,
//			ProtocolEncoderOutput out) throws Exception {
//		Buffer buffer = (Buffer) message;
//		IoBuffer result = IoBuffer.allocate(buffer.length+3);
//		result.putShort((short)(buffer.length+3));
//		result.put((byte) buffer.type);
////		result.putShort((short)(buffer.length+2));
//		result.put(buffer.buff,buffer.offset,buffer.length);
////		result.put(new byte[]{1,2,3,4});
//		result.flip();
//		out.write(result);
//	}
	
	@Override
	protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
		if(msg instanceof Buffer) {
			Buffer buffer = (Buffer) msg;
			ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
			buf.writeShort(buffer.length + 3);
			buf.writeByte(buffer.type);
			buf.writeBytes(buffer.buff, buffer.offset, buffer.length);
			
			return buf;
		}
		return msg;
	}

}
